package com.vs.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.vs.dao.DocumentOperation;
import com.vs.model.CustomMessage;
import com.vs.model.DocSearchForm;
import com.vs.util.Constants;

public class DocListAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String next = "";

		System.out.println("DocListAction execute called");
		DocSearchForm searchForm = (DocSearchForm) form;

		ArrayList<CustomMessage> customErrors = new ArrayList<CustomMessage>();
		List<DocSearchForm> docList = null;

		DocumentOperation docOperation = new DocumentOperation();

		String action = request.getParameter("action");
		Constants.log.debug("action1=" + action);
		System.out.println("action1=" + action);

		if (action == null) {
			action = searchForm.getAction();
			System.out.println("action2=" + action);
			Constants.log.debug("action2=" + action);
		}

		if (action != null) {
			if (action.equals("selectAll")) {
				next = "success";
			}
			if (action.equals("download")) {
				response.setContentType("application/octet-stream");
		        response.setHeader("Content-Disposition","attachment;filename=aac.jpg");
				next = "success";
				
				File file = new File(searchForm.getFilePath());
				FileInputStream fileIn = new FileInputStream(file);
				ServletOutputStream out = response.getOutputStream();
				 
				byte[] outputByte = new byte[4096];
				//copy binary contect to output stream
				while(fileIn.read(outputByte, 0, 4096) != -1)
				{
					out.write(outputByte, 0, 4096);
				}
				fileIn.close();
				out.flush();
				out.close();
				return null;
			}
			if (action.equals("delete")) {
				Integer docId = searchForm.getDocId();
				DocSearchForm doc = docOperation.getDocInfo(docId);

				if (deleteDocument(doc.getFilePath())) {
					boolean result = docOperation.deleteDoc(docId);

					if (result) {
						next = "success";
						CustomMessage info = new CustomMessage();
						info.setMessageLevel(Constants.INFO);
						info.setMessageText("deletd document successfully "
								+ docId);
						customErrors.add(info);
					} else {
						next = "deleteError";
						CustomMessage info = new CustomMessage();
						info.setMessageLevel(Constants.ERROR);
						info.setMessageText("Error while deleting document from db Id "
								+ docId);
						customErrors.add(info);
					}
				} else {
					next = "deleteError";
					CustomMessage info = new CustomMessage();
					info.setMessageLevel(Constants.ERROR);
					info.setMessageText("Error while deleting document from drive Id "
							+ docId + ";doc.getFilePath()=" + doc.getFilePath());
					customErrors.add(info);
				}

			}
		}

		if (next.equals("success") || next.equals("deleteError")) {
			Integer projectId = searchForm.getProjectId();
			if (projectId == null) {
				projectId = Integer.parseInt(getActiveSession(request)
						.getAttribute("projectId").toString());
			}
			// docList = this.listDocuments(projectId);
			searchForm.setProjectId(projectId);
			docList = new DocumentOperation().getDocList(searchForm);
			if(docList==null || docList.size()==0)
			{
				CustomMessage info = new CustomMessage();
				info.setMessageLevel(Constants.INFO);
				info.setMessageText("At present, no documents are added to this project");
				customErrors.add(info);
			}
		}

		request.setAttribute("docList", docList);
		request.setAttribute("customErrors", customErrors);
		return mapping.findForward("success");
	}

	private HttpSession getActiveSession(HttpServletRequest request) {
		return request.getSession(false);
	}

	private boolean deleteDocument(String fileName) {
		File f = new File(fileName);
		return f.delete();
	}

	@SuppressWarnings("unused")
	private List<DocSearchForm> listDocuments(Integer projectId) {
		System.out
				.println("DocListAction listDocuments projectId=" + projectId);
		List<DocSearchForm> docList = new ArrayList<DocSearchForm>();
		String projectPath = Constants.UPLOAD_PATH + "/" + projectId;
		File rootFolder = new File(projectPath);
		String docs[] = rootFolder.list();
		for (int i = 0; i < docs.length; i++) {
			String actualFile = docs[i];
			String displayFile = actualFile.substring(
					actualFile.indexOf("_") + 1, actualFile.length());
			System.out.println("actualFile=" + actualFile + ";displayFile="
					+ displayFile);
			DocSearchForm doc = new DocSearchForm();
			doc.setProjectId(projectId);
			doc.setFileName(displayFile);
			doc.setFilePath(actualFile);
			docList.add(doc);
		}
		System.out.println("docList.size=" + docList.size());
		return docList;
	}
}
